import { Component, OnInit } from '@angular/core'
import { FormGroup, FormBuilder, Validators } from '@angular/forms'
import { take, tap } from 'rxjs/operators'
import { NzMessageService } from 'ng-zorro-antd'

import { NewPageAccessor } from '@shared/components/new-page/new-page.interface'
import { IBiz } from '@shared/interfaces/biz'
import { makeAllControlDirty } from 'app/utils/helpers'
import { I18NService } from '@core'
import { IDepositCollection } from '@shared/interfaces/deposit'
import { DepositDataService } from '../../deposit-data.service'

@Component({
  selector: 'app-deposit-new-system',
  templateUrl: './system.component.html',
  styleUrls: ['../../../../../shared/styles/new-page-form.less'],
})
export class DepositNewSystemComponent implements NewPageAccessor, OnInit {
  constructor(
    private fb: FormBuilder,
    private msg: NzMessageService,
    private i18n: I18NService,
    private dataService: DepositDataService,
  ) {}

  data: any
  payload: IBiz = {}
  form: FormGroup = this.fb.group({})

  ngOnInit() {
    this.dataService.depositData$.value$
      .pipe(
        tap(data => {
          this.form = this.fb.group({
            biz: [data, [Validators.required]],
          })
        }),
        take(1),
      )
      .subscribe()
  }

  checkValid(): boolean {
    if (!this.form.valid) {
      makeAllControlDirty(this.form)
      return false
    }

    if (!this.form.get('biz').value.intStoreCode) {
      const msg = this.trans('VALIDATION.REQUIRED_SELECT', { name: this.trans('GENERAL.BIZ_LEVEL.STORE')})
      this.msg.error(msg)
      return false
    }

    this.pushDataToStore()
    this.msg.success(this.trans('GENERAL.NOTIFICATION.VALIDATION_SUCCESS'))
    return true
  }

  pushDataToStore(): void {
    const data: IDepositCollection = this.form.get('biz').value
    this.dataService.setDepositData(data)
  }

  private trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
